package com.begye.smartloan.apptest.certify

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.begye.smartloan.apptest.MyApplication
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.doImageUpload
import com.util.utillib.util.imagecovert.ImageConvert
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream

class CertifyViewModel : ViewModel() {

    var type: String = ""

    var imageType: Int = 0
    var salaryImageList = mutableListOf<JSONObject>()
    var selfieImageList = mutableListOf<JSONObject>()

    private val _saveFangKuiSuccessLiveData = MutableLiveData<Boolean>()
    val onSaveFangKuiSuccessLiveData get() = _saveFangKuiSuccessLiveData

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    fun initSalaryImageList() {
        salaryImageList.clear()
        val obj = JSONObject().apply {
            put("isAdd", "YES")
        }
        salaryImageList.add(obj)
    }

    fun initSelfieImageList() {
        selfieImageList.clear()
    }

    fun salaryImageListRemove(index: Int) {
        if (index in salaryImageList.indices) {
            salaryImageList.removeAt(index)
        }

        if (salaryImageList.isEmpty()) {
            initSalaryImageList()
            return
        }

        val lastItemIsAdd = salaryImageList.last().optString("isAdd") == "YES"
        if (!lastItemIsAdd) {
            salaryImageList.add(JSONObject().apply {
                put("isAdd", "YES")
            })
        }
    }

    fun selfieImageListRemove(index: Int) {
        if (index in selfieImageList.indices) {
            selfieImageList.removeAt(index)
        }

        if (selfieImageList.isEmpty()) {
            initSalaryImageList()
            return
        }
    }


    fun isMaxImages(): Boolean {
        return salaryImageList.size >= 3
    }

    fun handleTakePictureResult(
        result: String?,
        onConversionCompleted: (Int, Bitmap?, Int) -> Unit,
        onUploadCompleted: (Int, String?, Int) -> Unit
    ) {
        try {
            println(result.toString())

            result?.let {
                val localPath = it
//                val thumpImg = imagePathToBitmap(localPath)

                val obj = JSONObject().apply {
                    put("isAdd", "NO")
                    put("path", localPath)
                }

                if (imageType == 0) {
                    salaryImageList.add(0, obj)
                    if (salaryImageList.size >= 4) {
                        salaryImageList.removeLast()
                    }
                } else {
                    selfieImageList.add(obj)
                    if (selfieImageList.size >= 4) {
                        selfieImageList.removeLast()
                    }
                }
                onConversionCompleted.invoke(0, null, 0)
                requestUploadImage(localPath, 0, 0, onUploadCompleted)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("Recycle")
    fun handlePhotoAlbumResult(
        context: Context,
        result: Uri?,
        onConversionCompleted: (Int, Bitmap?, Int) -> Unit,
        onUploadCompleted: (Int, String?, Int) -> Unit
    ) {
        try {
            println(result.toString())
            result?.let {
                val path = imageUriToLocalFile(context, it)
                //压缩图片
                ImageConvert.startConvertImage(context, File(path)) { localPath, thumpImg ->
                    val obj = JSONObject().apply {
                        put("isAdd", "NO")
                        put("path", localPath)
                    }
                    if (imageType == 0) {
                        salaryImageList.add(0, obj)
                        if (salaryImageList.size >= 4) {
                            salaryImageList.removeLast()
                        }
                    } else {
                        selfieImageList.add(obj)
                        if (selfieImageList.size >= 4) {
                            selfieImageList.removeLast()
                        }
                    }
                    onConversionCompleted.invoke(0, thumpImg, 0)
                    localPath?.let {
                        requestUploadImage(
                            localPath,
                            0,
                            0,
                            onUploadCompleted
                        )
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun imageUriToLocalFile(
        context: Context,
        contentURI: Uri
    ): String {
        try {
            println(contentURI.path)

            val imgDir = "${context.filesDir}${File.separator}${MyApplication.product}_TEMP_PICS"
            val dirFile = File(imgDir)
            if (!dirFile.exists()) {
                dirFile.mkdirs()
            }

            val outFilePath = "$imgDir${File.separator}${System.currentTimeMillis()}.jpg"
            val imgInputStream: InputStream =
                context.contentResolver.openInputStream(contentURI) ?: return ""
            val outFile = File(outFilePath)
            val buffer = ByteArray(1024)
            var len: Int
            val fos = FileOutputStream(outFile)
            while (imgInputStream.read(buffer).also { len = it } != -1) {
                fos.write(buffer, 0, len)
            }
            fos.flush()
            fos.close()
            imgInputStream.close()
            return outFilePath
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }

    private fun imagePathToBitmap(filePath: String?): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePath, options)
    }

    fun validSalaryUrls(): String {
        return salaryImageList
            .filter { it.optString("isAdd") == "NO" }
            .mapNotNull { it.optString("url").takeIf { url -> url.isNotBlank() } }
            .joinToString(",")
    }

    fun validSelfieUrls(): String {
        return selfieImageList
            .mapNotNull { it.optString("url").takeIf { url -> url.isNotBlank() } }
            .joinToString(",")
    }

    private fun requestUploadImage(
        filePath: String,
        type: Int,
        position: Int,
        onFinished: (Int, String?, Int) -> Unit
    ) {
        doImageUpload(
            filePath = filePath,
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    val url = jsonObject.optString("url", "")
                    if (url.isNotBlank()) {
                        if (imageType == 0) {
                            if (salaryImageList.size > 1) {
                                salaryImageList.first().apply {
                                    put("url", url)
                                }
                            }
                        } else {
                            if (selfieImageList.size > 0) {
                                selfieImageList.last().apply {
                                    put("url", url)
                                }
                            }
                        }
                        onFinished.invoke(type, url, position)

                    } else {
                        if (imageType == 0) {
                            if (salaryImageList.isNotEmpty()) {
                                salaryImageList.removeFirst()
                            } else {
                                initSalaryImageList()
                            }
                        } else {
                            if (selfieImageList.isNotEmpty()) {
                                selfieImageList.removeLast()
                            } else {
                                initSelfieImageList()
                            }
                        }
                        onFinished.invoke(type, null, position)
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                    if (imageType == 0) {
                        if (salaryImageList.isNotEmpty()) {
                            salaryImageList.removeFirst()
                        } else {
                            initSalaryImageList()
                        }
                    } else {
                        if (selfieImageList.isNotEmpty()) {
                            selfieImageList.removeLast()
                        } else {
                            initSelfieImageList()
                        }
                    }
                    onFinished.invoke(type, null, position)
                }
            })
    }

}